<?php
/**
 * 
 * 密码重设
 * @author alang
 *
 */

class Api_resetpassword_mdl extends CI_Model
{
	
	
	public function __construct()
	{
		parent::__construct();
	}
	
	
	public function outputdata($data)
	{
		if ( !empty( $data['EMAIL'] ) && !empty( $data['RETCODE'] ) && !empty( $data['NEWPASSWORD'] ) ) {
			
			$user = $this->_checkUser( $data['EMAIL'] );
			if ( $user ) {
				//用户存在
				$ret = array();
				$ret = $this->_checkRetcode($user['uid'], $data['RETCODE']);
				if ( $ret ){
					//存在申请
					$password = Common::do_hash( $data['NEWPASSWORD'] );
					//修改密码
					$this->_changePassword($user['uid'],$password);
					//修改申请状态
					$retinfo = array( 'used' =>1);
					$this->_changeRetStatus( $ret['id'],$retinfo );
					
					$outputdata['TAG'] = $data['TAG'];
					$outputdata['STATUS'] = 0;
					$outputdata['ERRORMESSAGE'] = 'SUCCESSFULL';
					
				} else {
					
					//不存在或者过期
					$outputdata['TAG'] = $data['TAG'];
					$outputdata['STATUS'] = 1;
					$outputdata['ERRORMESSAGE'] = 'Expired or none';
					
				}
				
			} else {
				//用户不存在
				$outputdata['TAG'] = $data['TAG'];
				$outputdata['STATUS'] = 1;
				$outputdata['ERRORMESSAGE'] = 'NO USER';
				
			}
		} else {
			
			//信息不全
			$outputdata['TAG'] = $data['TAG'];
			$outputdata['STATUS'] = 1;
			$outputdata['ERRORMESSAGE'] = 'INFO ERROR';
			
		}
				
		header('Content-Type:text/html; charset=utf-8', false);
		echo json_encode($outputdata);
	}
	
	
	/**
	 * 
	 * 验证用户是否存在
	 * @param String $email
	 */
	private function _checkUser( $email )
	{
		$user = array();
		$user = $this->db->select( 'uid,txusername,txemail,active,lastlogin,txpassword,txgoldnum' )
						->where( 'txemail', $email )
						->get( 'cj_users' )
						->row_array();
		return $user;
	}
	
	/**
	 * 验证找回验证码是否正确
	 */
	private function _checkRetcode( $uid,$retcode )
	{
		$ret = array();
		$ret = $this->db->select( 'id,retcode,used' )
						->from( 'cj_retpassword' )
						->where( 'uid', $uid )
						->where( 'retcode', $retcode )
						->where( 'used', 0)
						->get()
						->row_array();
		return $ret;
	}
	
	/**
	 * 
	 * 修改密码
	 * @param int $uid
	 * @param String $password
	 */
	private function _changePassword($uid,$password)
	{
		$data = array( 'txpassword' => $password );
		
		$this->db->where( 'uid', $uid );	
		return $this->db->update( 'cj_users', $data );
		
	}
	
	private function _changeRetStatus( $id,$data )
	{
		$this->db->where( 'id', $id );	
		return $this->db->update( 'cj_retpassword', $data );
	}
	
	
}